/**
 * 
 */
package com.tool.finances.lifestyle;

import java.util.ArrayList;

import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.provider.BaseColumns;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.tool.finance.manager.ShareperfrenceManager;
import com.tool.finances.lifestyle.data.AccountProvider;
import com.tool.finances.lifestyle.data.AccountType;

/**
 * @author Captain
 * 
 */
public class StatisticsActivity extends ListActivity {

	private static ArrayList<AccountModel> list;

	private DetailAdapter detailAdapter;

	private String selectionString = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.statistics_detail);
		setTitle("统计");
		list = new ArrayList<AccountModel>();
		detailAdapter = new DetailAdapter(this);
		setListAdapter(detailAdapter);

	}

	@Override
	protected void onResume() {
		initList(selectionString);
		setListAdapter(detailAdapter);

		super.onResume();
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch (resultCode) {
		case RESULT_OK:
			selectionString = data.getExtras().getString("selection");
			break;
		case RESULT_CANCELED:
			selectionString = null;
			break;
		default:
			break;
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// menu.add(0, Menu.FIRST, 0, "Show All").setIcon(
		// new BitmapDrawable(BitmapFactory.decodeResource(getResources(),
		// R.drawable.icon_menu_refresh)));
		menu.add(0, Menu.FIRST + 1, 0, "搜索").setTitle("搜索").setIcon(
				new BitmapDrawable(BitmapFactory.decodeResource(getResources(),
						R.drawable.ic_menu_search)));
		menu.add(0, Menu.FIRST + 2, 0, "统计").setTitle("统计")
				.setIcon(
						new BitmapDrawable(BitmapFactory
								.decodeResource(getResources(),
										R.drawable.ic_menu_sort_by_size)));
		// menu.add(0, Menu.FIRST + 3, 0, "全部选择").setIcon(
		// new BitmapDrawable(BitmapFactory.decodeResource(getResources(),
		// R.drawable.ic_menu_mark)));
		menu.add(0, Menu.FIRST + 4, 0, "删除选中项").setIcon(
				new BitmapDrawable(BitmapFactory.decodeResource(getResources(),
						R.drawable.ic_menu_clear_playlist)));
		return super.onCreateOptionsMenu(menu);
	}

	private View staticsView;

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case Menu.FIRST:
			selectionString = null;
			onResume();
			break;
		case Menu.FIRST + 1:
			final Intent intent = new Intent(StatisticsActivity.this,
					SearchActivity.class);
			startActivityForResult(intent, 1);
			break;
		case Menu.FIRST + 2:
			allover = 0f;
			income = 0f;
			outcome = 0f;
			if (list.size() > 0) {
				for (final AccountModel model : list) {
					if (model.isChecked()) {
						allover += Float.parseFloat(model.getAccountMoney());
						if (model.getInOrOut().equalsIgnoreCase("true")) {
							income += Float.parseFloat(model.getAccountMoney());
						} else {
							outcome += Float
									.parseFloat(model.getAccountMoney());
						}
					}
				}

				staticsView = LayoutInflater.from(StatisticsActivity.this)
						.inflate(R.layout.statistics, null);
				final TextView allDataView = (TextView) staticsView
						.findViewById(R.id.allDataTextView);
				final TextView selectedincomeView = (TextView) staticsView
						.findViewById(R.id.selectedDataTextView);
				final TextView outcomeTextView = (TextView) staticsView
						.findViewById(R.id.outcomeTextView);
				allDataView.setText(allover.toString());
				selectedincomeView.setText(income.toString());
				outcomeTextView.setText(outcome.toString());

				new AlertDialog.Builder(StatisticsActivity.this).setTitle(
						"Statistics").setView(staticsView).create().show();
			} else {
				Toast.makeText(StatisticsActivity.this, "Statistics is empty",
						1000).show();
			}

			break;
		// case Menu.FIRST + 3:
		// if (item.getTitle().toString().equalsIgnoreCase("Select all")) {
		// for (AccountModel model : list) {
		// model.setChecked(true);
		// }
		// item.setTitle("Cancel ").setIcon(
		// new BitmapDrawable(BitmapFactory.decodeResource(
		// getResources(), R.drawable.ic_menu_deselect)));
		// } else {
		// for (AccountModel model : list) {
		// model.setChecked(false);
		// }
		// item.setTitle("Select all").setIcon(
		// new BitmapDrawable(BitmapFactory.decodeResource(
		// getResources(), R.drawable.ic_menu_mark)));
		// }
		// detailAdapter.notifyDataSetChanged();
		// break;
		case Menu.FIRST + 4:
			if (list.size() > 0) {
				int n = 0;
				for (final AccountModel model : list) {
					final int id = model.getAccountId();
					if (model.isChecked()) {
						getContentResolver().delete(
								AccountProvider.ACCOUNT_CONTENT_URI,
								"_id = " + id, null);
						n++;
					}
				}
				if (n > 0)
					Toast.makeText(StatisticsActivity.this,
							"Delete successfully", 1000).show();
			}
			onResume();
			break;
		default:
			break;
		}
		return super.onOptionsItemSelected(item);
	}

	private Float allover = 0f;
	private Float income = 0f;
	private Float outcome = 0f;

	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {

		final TextView textDateView = (TextView) v.findViewById(R.id.TextDate);
		final TextView textCategroyView = (TextView) v
				.findViewById(R.id.TextCategory);
		final TextView textMoneyView = (TextView) v.findViewById(R.id.TextMoney);
		final TextView textIdView = (TextView) v.findViewById(R.id.TextID);
		final TextView textCommentView = (TextView) v
				.findViewById(R.id.TextViewComment);

		final Intent intent = new Intent(StatisticsActivity.this, EditeActivity.class);
		intent.putExtra("Date", textDateView.getText().toString());
		intent.putExtra("Amount", textMoneyView.getText().toString());
		intent.putExtra("Category", textCategroyView.getText().toString());
		intent.putExtra("Comment", textCommentView.getText().toString());
		intent.putExtra("Id", textIdView.getText().toString());
		startActivity(intent);
	}

	private void initList(String selection) {
		final Cursor mCursor = getContentResolver().query(
				AccountProvider.ACCOUNT_CONTENT_URI,
				AccountType.Account.PROJECTION, selection, null, null);

		if (list.size() > 0) {
			list.clear();
		}

		if (mCursor.moveToFirst()) {
			do {
				final AccountModel accountModel = new AccountModel();
				int indexName = mCursor.getColumnIndex(BaseColumns._ID);
				final int accountInt = mCursor.getInt(indexName);
				accountModel.setAccountId(accountInt);

				indexName = mCursor
						.getColumnIndex(AccountType.Account.ACCOUNTDATE);
				String accountInfo = mCursor.getString(indexName);
				accountModel.setAccountDate(accountInfo);

				indexName = mCursor
						.getColumnIndex(AccountType.Account.ACCOUNTMONEY);
				accountInfo = mCursor.getString(indexName);
				accountModel.setAccountMoney(accountInfo);

				indexName = mCursor
						.getColumnIndex(AccountType.Account.ACCOUNTTYPE);
				accountInfo = mCursor.getString(indexName);
				accountModel.setAccountType(accountInfo);

				indexName = mCursor.getColumnIndex(AccountType.Account.INOROUT);
				accountInfo = mCursor.getString(indexName);
				accountModel.setInOrOut(accountInfo);

				final ShareperfrenceManager mShareperfrenceManager = new ShareperfrenceManager(
						StatisticsActivity.this);
				// indexName = mCursor
				// .getColumnIndex(AccountType.Account.MONEYTYPE);
				// accountInfo = mCursor.getString(indexName);
				accountModel.setMoneyType(mShareperfrenceManager.getUnit());

				indexName = mCursor.getColumnIndex(AccountType.Account.COMMENT);
				accountInfo = mCursor.getString(indexName);
				accountModel.setComment(accountInfo);
				accountModel.setChecked(false);

				list.add(accountModel);
			} while (mCursor.moveToNext());
		}
	}

	public class DetailAdapter extends BaseAdapter {

		private final Context mContext;

		public DetailAdapter(Context context) {
			mContext = context;
		}

		@Override
		public int getCount() {
			return list.size();
		}

		@Override
		public Object getItem(int position) {
			return null;// list.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			try {
				if (convertView == null) {
					convertView = LayoutInflater.from(mContext).inflate(
							R.layout.detailitem, null);
				}
				;

				final AccountModel accountModel = list.get(position);

				final CheckBox isSelectedBox = (CheckBox) convertView
						.findViewById(R.id.IsSelectedCheckBox);
				isSelectedBox.setTag(accountModel);
				isSelectedBox.setChecked(accountModel.isChecked());

				isSelectedBox
						.setOnCheckedChangeListener(new OnCheckedChangeListener() {

							@Override
							public void onCheckedChanged(
									CompoundButton buttonView, boolean isChecked) {
								final AccountModel accountModel = (AccountModel) buttonView
										.getTag();
								accountModel.setChecked(isChecked);
							}

						});

				final ImageView imageView = (ImageView) convertView
						.findViewById(R.id.ImageInOrOut);
				final TextView textDateView = (TextView) convertView
						.findViewById(R.id.TextDate);
				final TextView textCategroyView = (TextView) convertView
						.findViewById(R.id.TextCategory);
				final TextView textMoneyView = (TextView) convertView
						.findViewById(R.id.TextMoney);
				final TextView textMoenyTypeView = (TextView) convertView
						.findViewById(R.id.TextMoneyType);
				final TextView textIDView = (TextView) convertView
						.findViewById(R.id.TextID);
				final TextView commentTextView = (TextView) convertView
						.findViewById(R.id.TextViewComment);

				textDateView.setText(accountModel.getAccountDate());
				textMoneyView.setText(accountModel.getAccountMoney());
				textCategroyView.setText(accountModel.getAccountType());
				if (accountModel.getInOrOut().equalsIgnoreCase("True")) {
					imageView.setBackgroundResource(R.drawable.incommingmoney);
				} else {
					imageView.setBackgroundResource(R.drawable.outgoingmoney);
				}
				textMoenyTypeView.setText(accountModel.getMoneyType());
				commentTextView.setText(accountModel.getComment());

				textIDView.setText(String.valueOf(accountModel.getAccountId()));
				textIDView.setVisibility(android.view.View.INVISIBLE);

				return convertView;
			} catch (final Exception e) {
				return null;
			}
		}
	}
}
